package com.example.service;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class OllamaConversationService {

    private final ChatClient chatClient;


    @Autowired
    ChatMemory memory;

    @Autowired
    public OllamaConversationService(ChatClient chatClient) {
        this.chatClient = chatClient;
    }

    public String startConversation(String message) {
        String conversationId = UUID.randomUUID().toString();

        MessageChatMemoryAdvisor messageChatMemoryAdvisor = new MessageChatMemoryAdvisor(memory, conversationId, 20, 1);

        String response = chatClient.prompt()
                .user(message)
                .advisors(messageChatMemoryAdvisor)
                .call()
                .content();

        System.out.println("ConversationId : " + conversationId);
        return "ConversationId : " + conversationId + "\nResponse: " + response;
    }

    public String continueConversation(String conversationId, String message) {

        MessageChatMemoryAdvisor messageChatMemoryAdvisor = new MessageChatMemoryAdvisor(memory, conversationId, 20, 1);
        return chatClient.prompt()
                .user(message)
                .advisors(messageChatMemoryAdvisor)
                .call()
                .content();
    }

    public List<Message> getMessageList(String conversationId) {
        List<Message> messageList = memory.get(conversationId, 20);
        return messageList;
    }
}